package com.sikadwafastdaisfondturbo.pretloan.ui.credit.page

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.AmountAdapter
import com.sikadwafastdaisfondturbo.pretloan.adapter.CreditRepayLableAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageRepayBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：待还款
 */
class RepayPage: ProFragment() {
    lateinit var binding: PageRepayBinding

    private var mAmountAdapter: AmountAdapter? = null
    //还款明细
    private var mLableAdapter: CreditRepayLableAdapter? = null
    //是否展开
    private var isOpen = false

    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        binding.parentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        initRefreshView()
        initRvAmount()
        initRvRepayListView()
        showOpenOrCloseView()
    }

    override fun initListener() {
        binding.imgUser.setOnClickListener {
            showPersonalDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_USER,"CreditRepayment Page")
        }
        binding.imgKefu.setOnClickListener {
            showKefuDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"CreditRepayment Page")
        }
        //展开、收起
        binding.ivLable.setOnClickListener {
            isOpen = !isOpen
            showOpenOrCloseView()
        }
        //还款
        binding.btnRepayment.setOnClickListener {
            showLoading()
            onPayAction()
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT,"")
        }
    }

    override fun initData() {
        showLoading()
        loadCreditRepayInfoAction()
    }

    fun refreshAction(){
        loadCreditRepayInfoAction()
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)

            loadCreditRepayInfoAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    private fun initRvAmount(){
        binding.rvAmount.setHasFixedSize(true)
        binding.rvAmount.isNestedScrollingEnabled = false
        binding.rvAmount.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(14f)
        binding.rvAmount.addItemDecoration(LinearDecoration(0,decoration,0,0))
        val layoutManager = LinearLayoutManager(getContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.rvAmount.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(binding.rvAmount)
        mAmountAdapter!!.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter!!.getItem(position)
        }
        binding.rvAmount.adapter = mAmountAdapter
    }


    /**
     * 初始化列表
     */
    private fun initRvRepayListView() {
        binding.rvRepayInfo.setHasFixedSize(true)
        binding.rvRepayInfo.isNestedScrollingEnabled = false
        binding.rvRepayInfo.isFocusableInTouchMode = false //不需要焦点
        binding.rvRepayInfo.layoutManager = LinearLayoutManager(context)
        val topDecoration = DensityUtils.dp2px(20f)
        binding.rvRepayInfo.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        mLableAdapter = CreditRepayLableAdapter(binding.rvRepayInfo)
        binding.rvRepayInfo.adapter = mLableAdapter!!
        binding.rvRepayInfo.itemAnimator = DefaultItemAnimator()
        mLableAdapter!!.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        })
    }

    /**
     * 收起
     */
    private fun showOpenOrCloseView(){
        if (isOpen){//展开
            binding.rvRepayInfo.visibility = View.VISIBLE
            binding.ivLable.setImageResource(R.mipmap.img_credit_repay_up_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_OPEN,"")
        } else {
            binding.rvRepayInfo.visibility = View.GONE
            binding.ivLable.setImageResource(R.mipmap.img_credit_repay_down_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_CLOSE,"")
        }
    }

    /**
     * 设置还款信息
     */
    @SuppressLint("SetTextI18n")
    fun setRepaymentInfo(data: JSONObject) {
        val amountList = arrayListOf<String>()
        val amountString = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter!!.data = amountList

        binding.textRepayAmount.text = data.optString("repayAmount") + " " + data.optString("currency")
        binding.textRepayDate.text = data.optString("repayDate")
        binding.textTotal.text = data.optString("repayAmount")
        binding.textUnit.text = data.optString("currency")

        val jsArray = data.optJSONArray("repayList")
        val dataList = arrayListOf<JSONObject>()
        if (jsArray != null) {
            for (i in 0..<jsArray.length()){
                dataList.add(jsArray.optJSONObject(i))
            }
        }
        mLableAdapter!!.data = dataList
    }

    /**
     * 跳转支付H5
     */
    private fun enterPayLink(payUrl: String){
        val uri = Uri.parse(payUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * 获取还款信息
     */
    private fun loadCreditRepayInfoAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_INFO)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //某些地区没有repayList，需要手动添加数据
                if (!obj!!.has("repayList") || obj.optJSONArray("repayList") == null){
                    val unit = obj.optString("currency")
                    val repayArray = JSONArray()
                    val amountItem = JSONObject()
                    amountItem.put("showName",context!!.getString(R.string.credit_repaylist_loan_amount))
                    amountItem.put("showDetail",obj.optString("amount") + unit)
                    repayArray.put(amountItem)

                    val interestItem = JSONObject()
                    interestItem.put("showName",context!!.getString(R.string.credit_repaylist_interest))
                    interestItem.put("showDetail",obj.optString("interest") + unit)
                    repayArray.put(interestItem)

                    val serviceFeeItem = JSONObject()
                    serviceFeeItem.put("showName",context!!.getString(R.string.credit_repaylist_service_fee))
                    serviceFeeItem.put("showDetail",obj.optString("serviceFee") + unit)
                    repayArray.put(serviceFeeItem)

                    val overdueDayItem = JSONObject()
                    overdueDayItem.put("showName",context!!.getString(R.string.credit_repaylist_overdue_days))
                    overdueDayItem.put("showDetail",String.format(context!!.getString(R.string.credit_repaylist_days),obj.optString("overdueDay")))
                    repayArray.put(overdueDayItem)

                    val overduePenaltyItem = JSONObject()
                    overduePenaltyItem.put("showName",context!!.getString(R.string.credit_repaylist_overdue_penalty))
                    overduePenaltyItem.put("showDetail",obj.optString("overdueAmount") + unit)
                    repayArray.put(overduePenaltyItem)
                    obj.put("repayList",repayArray)
                }
                setRepaymentInfo(obj)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                binding.refreshLayout.finishRefresh()
            }
        })
    }

    /**
     * 还款
     */
    private fun onPayAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_URL)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                val repayUrl = obj.optString("repayUrl")
                val url =obj.optString("url")
                enterPayLink(repayUrl)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_CREDIT_REPAYMENT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_CREDIT_REPAYMENT_END,"")
    }
}